<template>
  <div class="breadcrumb">
    <div class="breadcrumb-title">
      <div class="breadcrumb-title-back" @click="back()">
        <el-icon><Back /></el-icon> 返回
      </div>
      | {{ breadcrumbList[breadcrumbList.length - 1].meta.title }}
    </div>
    <div class="breadcrumb-items">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="item in breadcrumbList"
          :key="item.path"
          :to="getPath(item)"
        >
          {{ item.meta.title }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElBreadcrumb, ElBreadcrumbItem } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import type { RouteLocationMatched } from 'vue-router';
import { computed } from 'vue';

const currentRoute = useRoute();

const router = useRouter();

const back = () => {
  router.back();
};

const getPath = (item: RouteLocationMatched): string | Object => {
  if (!item) return '';
  if (item.meta?.isReadonlyBreadcrumb) return '';
  return { path: item.redirect ? item.redirect : item.path };
};

const breadcrumbList = computed(() => {
  var result = currentRoute.matched.filter(
    (item) => !item.meta.isHideBreadcrumb
  );
  //如果第一个不是/，则添加/
  if (result[0].path.toLowerCase() != '/') {
    result.unshift({
      path: '/',
      meta: {
        title: '首页',
      },
    } as unknown as RouteLocationMatched);
  }
  return result;
});
</script>
<style lang="scss" scoped>
.breadcrumb {
  height: 10%;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e5e5e5;
  display: flex;
  align-items: center;
  font-size: 16px;
  box-sizing: border-box;
}
.breadcrumb-title {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  height: 100%;
  padding: 0 20px;
}
.breadcrumb-title-back {
  display: flex;
  align-items: center;
  cursor: pointer;
}
.breadcrumb-items {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}
</style>
